package com.bq.gametrade.ui.dialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.bq.gametrade.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Fei on 2015/12/15.
 */
public class UpdateAppDialog extends DialogFragment{

    private SharedPreferences preferences ;

    private Context mContext;
    private Activity activity;


    /* 下载包安装路径 */
    private static final String savePath = "/sdcard/bq/";

    private static final String saveFileName = savePath + "biqi.apk";

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressDialog progressDialog ;

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    progressDialog.setProgress(progress);
                    break;
                case DOWN_OVER:
                    progressDialog.dismiss();
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    private String updateApkUrl="",updateText="";
    private boolean isForcedUpdate;

    private View view;
    private TextView tv_prompt_title,tv_prompt_content;
    private Button btn_update,btn_noprompt;
    private View update_view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (Activity) getActivity();
        updateApkUrl = getArguments().getString("updateAppUrl");
        isForcedUpdate = getArguments().getBoolean("isForcedUpdate");
        updateText = getArguments().getString("text");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = inflater.inflate(R.layout.dialog_update_app, container);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        getDialog().show();

        initView();

        return  view;

    }

    private void initView(){
        tv_prompt_content = (TextView)view.findViewById(R.id.tv_prompt_content);
        if(!updateText.equals("")){
            tv_prompt_content.setText(updateText);
        }else {
            tv_prompt_content.setText("比奇交易平台已有新的版本,请更新！");
        }
        btn_update = (Button)view.findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDialog().dismiss();
                showDownloadDialog();


            }
        });
        btn_noprompt = (Button)view.findViewById(R.id.btn_noprompt);
        btn_noprompt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.update_appprompt,false);
                getDialog().dismiss();
            }
        });
        update_view = (View)view.findViewById(R.id.update_view);
        /**
         * f、选择更新
         * 2、强制更新
         */

        if(isForcedUpdate){
            update_view.setVisibility(View.GONE);
            btn_noprompt.setVisibility(View.GONE);
            setCancelable(false);
        }else {

            update_view.setVisibility(View.VISIBLE);
            btn_noprompt.setVisibility(View.VISIBLE);
        }

    }

    private void showDownloadDialog(){
        progressDialog =new ProgressDialog(activity);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressNumberFormat("");
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                interceptFlag = true;
                dialog.dismiss();
            }
        });
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "后台下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.update_appprompt, true);
                dialog.dismiss();
            }
        });
        progressDialog.show();

        downloadApk();
    }


    /**
     * 下载apk
     * @param
     */
    private void downloadApk(){
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(updateApkUrl);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if(!file.exists()){
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100+1);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }

        }
    };
    /**
     * 安装apk
     * @param
     */
    private void installApk(){
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        activity.startActivity(i);

        preferences = activity.getSharedPreferences("count", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putInt("count", 0);
        //提交修改
        editor.commit();
        android.os.Process.killProcess(android.os.Process.myPid());
    }



}
